using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;

namespace MCromwell.StaffIntranet.Data.NHibernate.Test
{
    public class DataAccessHelper : IDisposable
    {
        private string connectionString = string.Empty;
        private DbProviderFactory factory = null;
        private IDbConnection connection = null;

        public DataAccessHelper(string connectionString, DbProviderFactory DBFactory)
        {
            this.connectionString = connectionString;
            this.factory = DBFactory;
        }

        public IDataReader ExecuteReader(string sql)
        {
            CreateConnection();
            IDbCommand cmd = connection.CreateCommand();
            cmd.CommandText = sql;
            cmd.CommandType = CommandType.Text;
            return cmd.ExecuteReader();
        }

        public T ExecuteScalar<T>(string sql)
        {
            CreateConnection();
            IDbCommand cmd = connection.CreateCommand();
            cmd.CommandText = sql;
            cmd.CommandType = CommandType.Text;
            return (T)cmd.ExecuteScalar();
        }

        private void CreateConnection()
        {
            connection = factory.CreateConnection();
            connection.ConnectionString = connectionString;
            connection.Open();
        }

        public void Dispose()
        {
            if ((connection != null) && (connection.State != ConnectionState.Closed))
                connection.Dispose();
        }

    }
}
